package pencil.controller;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pencil.service.pencil_service;
import pencil.to.blackSimTO;
import pencil.to.factoryMaterial2TO;
import pencil.to.holeMachineTO;
import pencil.to.holeNamuTO;
import pencil.to.insertMachineTO;
import pencil.to.pencilTO;
import pencil.util.pencilUtil;

//홈파인 나무판에 연필심 넣는 머신
@Controller
@RequestMapping("/insertMachine")
public class insertMachineController {
private pencil_service service;
ArrayList list = null;
insertMachineTO imto  = new insertMachineTO();
private int runStep=0;
//insertMachineTO imto  = new insertMachineTO(0, 0, 0, "", "", 0, 0, "", 0, 0);


	public void setService(pencil_service service){
		this.service= service;
	}
	
	@RequestMapping("/begin.do")
	public ModelAndView begin(String orderNumS) throws SQLException, InterruptedException{
		//0. 주문량에 필요한 재료계산
		int pencilNeed=Integer.parseInt(orderNumS);
		int order = pencilNeed;
		int normal=0;//성공된 제품의수
		int abnormal=0;//비정상 품
		list = new ArrayList();
//		가공된 재료 가져오기
		blackSimTO bsto = service.selectblackSim();
		
		if(bsto==null){
			System.out.println("연필심 재고가 하나도 없습니다.");
			// 메세지 처리 해야함
		}
		System.out.println("연필심 : " + bsto);
		
		holeNamuTO hnto = service.selectHoleNamu();
		
		if(hnto==null){
			System.out.println("홈나무판 재고가 하나도 없습니다.");
			// 메세지 처리 해야함
		}
		System.out.println("나무판 : " + hnto);
		
//		기계상태 가져오기
		imto  = service.selectInsertMInfo();
		System.out.println(imto);
		if(imto==null){
			imto = new insertMachineTO();
		}
		
		int needBs= pencilNeed;
		
		
		
//		pencilNeed  5 = simAmount 5 * namuAmout 2
		pencilNeed = pencilNeed/5;
		int needNamu =pencilNeed * 2;
		
		
		
		
		System.out.println( " ㅁㄴㅇ " + pencilNeed);
		
//		재고가 받아온 연필 오더 갯수를 만들수 있는지 확인하기
		if(needBs >= bsto.getAmount()){
			System.out.println("연필심이 부족합니다. 더 생산하십시요");
//			메세지 처리
		}
		
		if(needNamu >= hnto.getAmount()){
			System.out.println("홈나무판이 부족합니다. 더 생산하십시요");
//			메세지 처리
		}
		
		
		
//		창고에 연필 갯수에 맞게 각각 재료들을 출고 등록시키기
		int simAmount = bsto.getAmount() - needBs;
		bsto.setAmount(simAmount);
		bsto.setDateRegist(pencilUtil.getNow());
		bsto.setInvenInfo("출고 : -" + needBs);
		service.insertblackSim(bsto);
		
		
		int namuAmout = hnto.getAmount() - needNamu;
		hnto.setAmount(namuAmout);
		hnto.setDateRegist(pencilUtil.getNow());
		hnto.setInvenInfo("출고 : -" + needNamu);
		service.insertHoleNamu(hnto);
		
		
		int machineLife = imto.getMachineLife();
		
		

		
		System.out.println("재료 공정 시작");
		
		
		
//		hmto.setBoard(namuNeed);
		imto.setRunstep(pencilUtil.HolerunStep(pencilNeed));
		
		double run = imto.getRunstep();
	
		while(pencilNeed!=0){
			imto.setStartTime(pencilUtil.getNow());//시작시간
			
			//작동시간//
			Thread.sleep(1000);
			//
			
			int testValue=pencilUtil.troubleMaker(5, 10);//불량률 조절 매서드(기본값, 랜덤값)
	//		System.out.println("불량률:"+testValue );
		
			if(testValue>=7){//불량률 판별
				normal=normal+1;//성공품 증가
				imto.setState("정상");
			}else{
				abnormal=abnormal+1;
				imto.setState("불량");
			}
			
			machineLife++;
			pencilNeed--;
			
			
			imto.setBlackStick(needBs);
			imto.setHoleBoard(needNamu);
			imto.setNormal(normal);
			imto.setMachineLife(machineLife);
			imto.setEndTime(pencilUtil.getNow());
			imto.setAbnormal(abnormal);
			
			
			
			
			System.out.println("연필심 개수 : " + needBs);
			System.out.println("나무판 개수 : " + needNamu);
			System.out.println("정상품 개수 " + normal);
			System.out.println("불량품 개수 " + abnormal);
			System.out.println("진행률:"+(int)imto.getRunstep());
			imto.setRunstep(imto.getRunstep() + run);
			if(imto.getRunstep() >= 100){
				
				imto.setRunstep(100);
			}
			service.insertInsertMInfo(imto);
			
			needBs = needBs - 5;
			needNamu = needNamu - 2;
			
			
			
			pencilTO pto = service.selectPencil();
			
			if(pto==null){
				pto = new pencilTO();
			}
			
			pto.setDateRegist(pencilUtil.getNow());
			pto.setInvenInfo("입고");
			pto.setCount(pto.getCount() + 5);
		
			service.insertPencil(pto);
			
		}
		
	
		System.out.println(" 오더 연필수 수 : " + orderNumS);
		System.out.println(imto);

		
	return null;
		
	}
	
	@RequestMapping("/getmoniser.do")
	public void bannerItem(HttpServletRequest request,HttpServletResponse response)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		System.out.println("제이슨 호출");
	
	///////////////////////////////////////////////
		
//		holeMachineTO htto1= service.selectHoleMInfo();
//		hmto.setRunstep(runStep);
//		insertMachineTO imto  = service.selectInsertMInfo();
//		list.add(imto);
		String responseMsg =null;
		JSONObject jobj= new JSONObject(imto);
		responseMsg = jobj.toString();
		PrintWriter out = response.getWriter();
		System.out.println(responseMsg);
		out.print(responseMsg);
		return;
	}
	
	@RequestMapping("/getReport.do")
	public void getReport(HttpServletRequest request,HttpServletResponse response)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		System.out.println("리포트 호출");
	
	///////////////////////////////////////////////
		
//		holeMachineTO htto1= service.selectHoleMInfo();
//		hmto.setRunstep(runStep);
		
		String responseMsg =null;
		JSONArray jobj= new JSONArray(list);
		responseMsg = jobj.toString();
		PrintWriter out = response.getWriter();
		System.out.println(responseMsg);
		out.print(responseMsg);
		return;
	}
	
	
	
	@RequestMapping("/getPencil.do")
	public void getPencil(HttpServletRequest request,HttpServletResponse response)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		System.out.println("연필 개수 호출");
	
	///////////////////////////////////////////////
		
//		holeMachineTO htto1= service.selectHoleMInfo();
//		hmto.setRunstep(runStep);
		pencilTO pen = service.selectPencil();
		
	
		String responseMsg =null;
		JSONObject jobj= new JSONObject(pen);
		responseMsg = jobj.toString();
		PrintWriter out = response.getWriter();
		System.out.println(responseMsg);
		out.print(responseMsg);
		return;
	}
	
	
}
